package com.zls;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zls.pojo.Article;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)
public class demo02 {
    @Autowired
    private TransportClient transportClient;

    @Autowired
    private ObjectMapper objectMapper;
    @Test
    public void createIndex() {
        //准备创建索引 ，指定索引名 执行创建的动作（get方法）
        transportClient.admin().indices().prepareCreate("blog03").get();
    }
    //删除索引
    @Test
    public void deleteIndex() {
        //准备删除索引 ，指定索引名 指定删除的动作（get）
        transportClient.admin().indices().prepareDelete("blog02").get();
    }
    @Test
    public void putMapping() throws Exception {
        //1.创建索引 如果已有索引 可以先删除再测试
        transportClient.admin().indices().prepareCreate("blog02").get();

        //2.创建映射
        XContentBuilder builder = XContentFactory.jsonBuilder()
                .startObject()
                .startObject("article")
                .startObject("properties")
                .startObject("id")
                .field("type", "long").field("store", "true")
                .endObject()
                .startObject("title")
                .field("type", "text").field("analyzer", "ik_smart").field("store", "true")
                .endObject()
                .startObject("content")
                .field("type", "text").field("analyzer", "ik_smart").field("store", "true")
                .endObject()
                .endObject()
                .endObject()
                .endObject();

        PutMappingRequest mapping = new PutMappingRequest("blog02").type("article").source(builder);

        transportClient.admin().indices().putMapping(mapping).get();
    }

    //创建文档 /更新文档 使用的是ik分词器
    //通过ObjctMapper进行创建
    @Test
    public void createIndexAndDocument() throws Exception {
        //设置数据
        Article article = new Article();
        article.setTitle("华为手机很棒");
        article.setContent("华为手机真的很棒");
        article.setId(1L);
        IndexResponse indexResponse = transportClient
                .prepareIndex("blog02", "article", "1")
                .setSource(objectMapper.writeValueAsString(article), XContentType.JSON)
                .get();
        System.out.println(indexResponse);
    }
    //使用xcontentBuidler方式进行创建
    /**
     * {
     *     "id": 1,
     *     "content": "华为手机真的很棒",
     *     "title": "华为手机很棒"
     * }
     */
    @Test
    public void createDocumentByJsons() throws Exception{
        XContentBuilder xContentBuilder= XContentFactory.jsonBuilder()
                .startObject()
                .field("id",2)
                .field("content","华为手机真的很棒")
                .field("title","华为手机很棒")
                .endObject();
        IndexResponse indexResponse = transportClient.prepareIndex("blog02", "article", "4")
                .setSource(xContentBuilder).get();
        System.out.println(indexResponse);
    }
    //删除文档
    @Test
    public void deleteByDocument() {
        transportClient.prepareDelete("blog02", "article", "4").get();
    }

    @Test
    public void createDocument() throws Exception {
        //构建批量添加builder
        BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();
        long start=System.currentTimeMillis();
        for (long i = 1; i < 100000 ; i++) {
            //数据构建
            Article article = new Article();
            article.setTitle("华为手机很棒" + i);
            article.setContent("华为手机真的很棒啊" + i);
            article.setId(i);
            //转成json
            String s = objectMapper.writeValueAsString(article);
            //设置值
            IndexRequest source =
                    new IndexRequest("blog02", "article", "" + i).source(s, XContentType.JSON);
            //添加请求对象buidler中
            bulkRequestBuilder.add(source);
        }
        //一次性提交
        BulkResponse bulkItemResponses = bulkRequestBuilder.get();
        long end = System.currentTimeMillis();
        System.out.println("消耗了:"+(end-start));


        System.out.println("获取状态：" + bulkItemResponses.status());
        if (bulkItemResponses.hasFailures()) {
            System.out.println("还有些--->有错误");
        }
    }

}
